import React, { useState, useRef, useEffect } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import * as Select from '@radix-ui/react-select';
import * as Popover from '@radix-ui/react-popover';
import { Cross2Icon, Cross1Icon } from '@radix-ui/react-icons';
import classNames from 'classnames';
import styles from './index.module.scss';

const FONTS = [
  { value: 'Noto Sans SC', label: 'Noto Sans SC' },
  { value: 'Arial', label: 'Arial' },
  { value: 'Helvetica', label: 'Helvetica' },
  { value: 'Times New Roman', label: 'Times New Roman' },
  { value: 'Georgia', label: 'Georgia' },
  { value: 'Courier New', label: 'Courier New' },
  { value: 'Microsoft YaHei', label: '微软雅黑' },
  { value: 'SimSun', label: '宋体' },
  { value: 'KaiTi', label: '楷体' },
];

const COLORS = [
  '#000000',
  '#434343',
  '#666666',
  '#999999',
  '#B7B7B7',
  '#CCCCCC',
  '#D9D9D9',
  '#FFFFFF',
  '#FF0000',
  '#FF4D00',
  '#FF9900',
  '#FFB800',
  '#FCE58D',
  '#F7E8D0',
  '#C7E3B4',
  '#7EC482',
  '#00FF00',
  '#0EB300',
  '#00FFFF',
  '#1BA1E2',
  '#0063B1',
  '#0000FF',
  '#4800FF',
  '#B300FF',
];

const SelectCodeUpdate = ({ isOpen, onClose, initialHtml, onSave }) => {
  // 存储当前的内容，但不用来控制编辑器
  const [content, setContent] = useState(initialHtml);
  const [fontFamily, setFontFamily] = useState('Arial');
  const [fontSize, setFontSize] = useState('14');
  const [textAlign, setTextAlign] = useState('left');
  const [textColor, setTextColor] = useState('#151515');
  const [isBold, setIsBold] = useState(false);
  const [isItalic, setIsItalic] = useState(false);
  const [isUnderline, setIsUnderline] = useState(false);
  const [hasUserEdited, setHasUserEdited] = useState(false);
  // Single state variable to control color picker modal
  const [colorModal, setColorModal] = useState(false);
  
  // 记录哪些样式被用户修改过
  const [modifiedStyles, setModifiedStyles] = useState({
    fontFamily: false,
    fontSize: false,
    textAlign: false,
    textColor: false,
    bold: false,
    italic: false,
    underline: false
  });
  
  // 创建一个ref来引用编辑器元素
  const editorRef = useRef(null);
  
  // 只在初始化时设置编辑器内容
  useEffect(() => {
    if (editorRef.current && initialHtml) {
      editorRef.current.innerHTML = initialHtml;
      // 重置用户编辑状态
      setHasUserEdited(false);
    }
  }, [initialHtml, isOpen]);
  
  // 自动保存功能 - 内容变化时触发
  useEffect(() => {
    // 只有在用户编辑后才触发保存
    if (editorRef.current && hasUserEdited) {
      // 添加延迟以避免过于频繁的保存
      const timer = setTimeout(() => {
        // 调用外部传入的自动保存回调
        if (onSave) {
          // 获取当前内容并应用样式
          const currentContent = prepareContentForSave();
          onSave(currentContent);
        }
      }, 500); // 0.5秒后触发保存
      
      return () => clearTimeout(timer); // 清除定时器
    }
  }, [content, fontFamily, fontSize, textAlign, textColor, isBold, isItalic, isUnderline, hasUserEdited]);
  
  // 准备要保存的内容，只应用用户修改过的样式
  const prepareContentForSave = () => {
    const currentContent = editorRef.current.innerHTML;
    
    // Parse the HTML content
    const parser = new DOMParser();
    const doc = parser.parseFromString(currentContent, 'text/html');
    const elements = doc.body.children;
    
    // 构建样式字符串
    const fontStyles = [];
    if (modifiedStyles.bold && isBold) fontStyles.push('font-weight: bold');
    if (modifiedStyles.italic && isItalic) fontStyles.push('font-style: italic');
    if (modifiedStyles.underline && isUnderline) fontStyles.push('text-decoration: underline');
    const fontStylesStr = fontStyles.join('; ');
    
    // Apply styles to each top-level element
    for (let element of elements) {
      // 只应用用户修改过的样式
      if (modifiedStyles.fontFamily) element.style.fontFamily = fontFamily;
      if (modifiedStyles.fontSize) element.style.fontSize = `${fontSize}px`;
      if (modifiedStyles.textAlign) element.style.textAlign = textAlign;
      if (modifiedStyles.textColor) element.style.color = textColor;
      
      // 应用文本样式
      if (modifiedStyles.bold && isBold) element.style.fontWeight = 'bold';
      if (modifiedStyles.italic && isItalic) element.style.fontStyle = 'italic';
      if (modifiedStyles.underline && isUnderline) element.style.textDecoration = 'underline';
    }
    
    // If no elements (pure text), wrap in a styled div
    if (elements.length > 0) {
      return doc.body.innerHTML;
    } else {
      // 只应用被修改过的样式
      const styles = [];
      if (modifiedStyles.fontFamily) styles.push(`font-family: ${fontFamily}`);
      if (modifiedStyles.fontSize) styles.push(`font-size: ${fontSize}px`);
      if (modifiedStyles.textAlign) styles.push(`text-align: ${textAlign}`);
      if (modifiedStyles.textColor) styles.push(`color: ${textColor}`);
      if (fontStylesStr) styles.push(fontStylesStr);
      
      return `<div${styles.length ? ` style="${styles.join('; ')}"` : ''}>${currentContent}</div>`;
    }
  };

  const handleSave = () => {
    // 使用公共函数准备内容
    const finalContent = prepareContentForSave();
    onSave(finalContent);
  };

  // 切换文本样式
  const toggleTextStyle = (style) => {
    switch (style) {
      case 'bold':
        setIsBold(!isBold);
        setModifiedStyles(prev => ({ ...prev, bold: true }));
        setHasUserEdited(true);
        break;
      case 'italic':
        setIsItalic(!isItalic);
        setModifiedStyles(prev => ({ ...prev, italic: true }));
        setHasUserEdited(true);
        break;
      case 'underline':
        setIsUnderline(!isUnderline);
        setModifiedStyles(prev => ({ ...prev, underline: true }));
        setHasUserEdited(true);
        break;
      default:
        break;
    }
  };

  return (
    <div className={styles.dialogContent}>
      <div className={styles.header}>
        <div className={styles.title}>编辑文本</div>
        <button 
          className={styles.closeButton} 
          onClick={onClose}
          aria-label="关闭"
        >
          <Cross2Icon />
        </button>
      </div>

      <div className={styles.toolbar}>
        <Select.Root value={fontFamily} onValueChange={(value) => {
            setFontFamily(value);
            setModifiedStyles(prev => ({ ...prev, fontFamily: true }));
            setHasUserEdited(true);
          }}>
          <Select.Trigger
            className={styles.selectTrigger}
            aria-label="Font family"
          >
            <Select.Value>{fontFamily}</Select.Value>
          </Select.Trigger>
          <Select.Portal>
            <Select.Content
              className={styles.selectContent}
              position="popper"
              sideOffset={5}
            >
              <Select.Viewport className={styles.selectViewport}>
                {FONTS.map((font) => (
                  <Select.Item
                    key={font.value}
                    value={font.value}
                    className={styles.selectItem}
                  >
                    <Select.ItemText style={{ fontFamily: font.value }}>
                      {font.label}
                    </Select.ItemText>
                  </Select.Item>
                ))}
              </Select.Viewport>
            </Select.Content>
          </Select.Portal>
        </Select.Root>

        <Select.Root value={fontSize} onValueChange={(value) => {
            setFontSize(value);
            setModifiedStyles(prev => ({ ...prev, fontSize: true }));
            setHasUserEdited(true);
          }}>
          <Select.Trigger
            className={styles.selectTrigger}
            aria-label="Font size"
          >
            <Select.Value>{fontSize}</Select.Value>
          </Select.Trigger>
          <Select.Portal>
            <Select.Content
              className={styles.selectContent}
              position="popper"
              sideOffset={5}
            >
              <Select.Viewport className={styles.selectViewport}>
                {[12, 14, 16, 18, 24, 36, 48, 64].map((size) => (
                  <Select.Item
                    key={size}
                    value={String(size)}
                    className={styles.selectItem}
                  >
                    <Select.ItemText>{size}</Select.ItemText>
                  </Select.Item>
                ))}
              </Select.Viewport>
            </Select.Content>
          </Select.Portal>
        </Select.Root>

        <div className={styles.colorPickerContainer}>
          <button
            className={styles.colorButton}
            aria-label="Pick text color"
            style={{ backgroundColor: textColor }}
            onClick={() => setColorModal(!colorModal)}
          />
          
          {colorModal && (
            <div className={styles.colorPickerContent}>
              <div className={styles.colorGrid}>
                {COLORS.map((color) => (
                  <button
                    key={color}
                    className={classNames(styles.colorOption, {
                      [styles.activeColor]: color === textColor,
                    })}
                    style={{ backgroundColor: color }}
                    onClick={() => {
                      setTextColor(color);
                      setModifiedStyles(prev => ({ ...prev, textColor: true }));
                      setHasUserEdited(true);
                      setColorModal(false);
                    }}
                    aria-label={`Select color ${color}`}
                  />
                ))}
              </div>
              <button 
                className={styles.closeButton} 
                aria-label="Close" 
                onClick={() => setColorModal(false)}
              >
                <Cross2Icon />
              </button>
            </div>
          )}
        </div>

        <div className={styles.formatButtons}>
          <button
            onClick={() => toggleTextStyle('bold')}
            className={classNames(styles.formatButton, {
              [styles.active]: isBold,
            })}
            aria-label="Bold"
          >
            B
          </button>
          <button
            onClick={() => toggleTextStyle('underline')}
            className={classNames(styles.formatButton, {
              [styles.active]: isUnderline,
            })}
            aria-label="Underline"
          >
            U
          </button>
          <button
            onClick={() => toggleTextStyle('italic')}
            className={classNames(styles.formatButton, {
              [styles.active]: isItalic,
            })}
            aria-label="Italic"
          >
            I
          </button>
        </div>

        <div className={styles.alignButtons}>
          <button
            onClick={() => {
            setTextAlign('left');
            setModifiedStyles(prev => ({ ...prev, textAlign: true }));
            setHasUserEdited(true);
          }}
            className={classNames(styles.alignButton, {
              [styles.active]: textAlign === 'left',
            })}
            aria-label="Align left"
          >
            ⫷
          </button>
          <button
            onClick={() => {
            setTextAlign('center');
            setModifiedStyles(prev => ({ ...prev, textAlign: true }));
            setHasUserEdited(true);
          }}
            className={classNames(styles.alignButton, {
              [styles.active]: textAlign === 'center',
            })}
            aria-label="Align center"
          >
            ≡
          </button>
          <button
            onClick={() => {
            setTextAlign('right');
            setModifiedStyles(prev => ({ ...prev, textAlign: true }));
            setHasUserEdited(true);
          }}
            className={classNames(styles.alignButton, {
              [styles.active]: textAlign === 'right',
            })}
            aria-label="Align right"
          >
            ⫸
          </button>
        </div>
      </div>

      <div
        ref={editorRef}
        className={styles.editor}
        contentEditable
        suppressContentEditableWarning={true}
        onInput={(e) => {
          // 只在内部跟踪内容变化，但不触发重新渲染
          // 这样光标位置就不会丢失
          setContent(e.currentTarget.innerHTML);
          setHasUserEdited(true);
        }}
        style={{
          fontFamily,
          fontSize: `${fontSize}px`,
          color: textColor,
          fontWeight: isBold ? 'bold' : 'normal',
          fontStyle: isItalic ? 'italic' : 'normal',
          textDecoration: isUnderline ? 'underline' : 'none',
        }}
      />

      {/* <div className={styles.footer}>
        <button onClick={handleSave} className={styles.saveButton}>
          已保存
        </button>
      </div> */}
    </div>
  );
};

export default SelectCodeUpdate;
